//
//  PikerViewController.swift
//  DemoProject
//
//  Created by hao on 2018/7/18.
//  Copyright © 2018年 hao. All rights reserved.
//

import UIKit

class PikerViewController: BaseTableViewController {

    let pickerView = UIPickerView()
    let pickerView1 = UIPickerView()
    let pickerView2 = UIPickerView()
    let pickerView3 = UIPickerView()
    
    let disposeBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupView()
        setupData()
        _rxSwiftProperty()
        _customPickviewAdapters()
    }
    
    private func setupView() {
        let height = self.tableHeadView.height/4
        self.tableHeadView.addSubview(pickerView)
        pickerView.snp.makeConstraints { (make) in
            make.left.top.right.equalTo(0)
            make.height.equalTo(height)
        }
        
        self.tableHeadView.addSubview(pickerView1)
        pickerView1.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(pickerView)
            make.top.equalTo(pickerView.snp.bottom)
        }
        
        self.tableHeadView.addSubview(pickerView2)
        pickerView2.snp.makeConstraints { (make) in
            make.left.right.height.equalTo(pickerView)
            make.top.equalTo(pickerView1.snp.bottom)
        }
        
        self.tableHeadView.addSubview(pickerView3)
        pickerView3.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(0)
            make.height.equalTo(height)
        }
    }
    
    private func _rxSwiftProperty() {
        // 绑定数据源
        Observable.just([1, 2, 3]).bind(to: pickerView.rx.itemTitles) { (row, item) in
            return "第\(row)行 -> \(item)项"
        }.disposed(by: disposeBag)
        // 绑定选中事件
        pickerView.rx.modelSelected(Int.self).subscribe(onNext: { models in
            print(info: "models selected count: \(models.count) -> arr \(models) -> value: \(models[0])")
        }).disposed(by: disposeBag)
        
        /// 设置字体样式
        Observable.just(["A", "B", "C"])
            .bind(to: pickerView1.rx.itemAttributedTitles) { _, item in
                return NSAttributedString(string: "\(item)",
                    attributes: [
                        NSAttributedStringKey.foregroundColor: UIColor.cyan,
                        NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleDouble.rawValue
                    ])
            }
            .disposed(by: disposeBag)
        
        pickerView1.rx.modelSelected(String.self)
            .subscribe(onNext: { models in
                print(info: "models selected count: \(models.count) -> arr \(models) -> value: \(models[0])")
            })
            .disposed(by: disposeBag)
        
        /// 设置颜色
        Observable.just([UIColor.red, UIColor.green, UIColor.blue])
            .bind(to: pickerView2.rx.items) { _, item, threeParam in
                let view = UIView()
                view.backgroundColor = item
                if let param3 = threeParam {
                    print(info: "param3 = \(param3)")
                }
                return view
            }
            .disposed(by: disposeBag)
        
        pickerView2.rx.modelSelected(UIColor.self)
            .subscribe(onNext: { models in
                print(info: "models selected count: \(models.count) -> arr \(models) -> value: \(models[0])")
            })
            .disposed(by: disposeBag)
    }
    
    /// 自定义适配器
    private func _customPickviewAdapters() {
        Observable.just([[1, 2, 3], [5, 8, 13], [21, 34]])
            .bind(to: pickerView3.rx.items(adapter: PickerViewViewAdapter()))
            .disposed(by: disposeBag)
        
        pickerView3.rx.modelSelected(Int.self).subscribe(onNext: { models in
            print(info: "models selected count: \(models.count) -> arr \(models) -> value: \(models[0])")
        }).disposed(by: disposeBag)
    }
    
    private func setupData() {
        let titles = ["numberOfComponents",
                      "返回component列中有多少行",
                      "返回component中一行的尺寸",
                      "showsSelectionIndicator",
                      "返回第component列每一行的高度",
                      "返回选中的是第component列的第几行",
                      "将图片作为选择框选项",
                      "修改选项的字体大小和颜色"]
        
        let descArr = ["返回UIPickerView当前的列数",
                       "- (NSInteger)numberOfRowsInComponent:(NSInteger)component;",
                       "-  (CGSize)rowSizeForComponent:(NSInteger)component;",
                       "是否显示指示器，默认为NO",
                       "- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component;",
                       "- (NSInteger)selectedRowInComponent:(NSInteger)component;",
                       """
                        选择框选项的内容，除了可以使字符串类型的，还可以是任意UIView类型的元素。比如我们将选项内容设置为图片：
                        func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int,
                                        reusing view: UIView?) -> UIView {
                            let image = UIImage(named:"icon_"+String(row))
                            let imageView = UIImageView()
                            imageView.image = image
                            return imageView
                        }
                       """,
                       """
                        func pickerView(_ pickerView: UIPickerView, viewForRow row: Int,
                        forComponent component: Int, reusing view: UIView?) -> UIView {
                            var pickerLabel = view as? UILabel
                            if pickerLabel == nil {
                                pickerLabel = UILabel()
                                pickerLabel?.font = UIFont.systemFont(ofSize: 13)
                                pickerLabel?.textAlignment = .center
                            }
                            pickerLabel?.text = String(row)+"-"+String(component)
                            pickerLabel?.textColor = UIColor.blue
                            return pickerLabel!
                        }
                       """]
        
        addTitles(titles, footDescs: descArr)
    }

}

/// 自定义适配器
fileprivate final class PickerViewViewAdapter
    : NSObject
    , UIPickerViewDataSource
    , UIPickerViewDelegate
    , RxPickerViewDataSourceType
    , SectionedViewDataSourceType {
    
    typealias Element = [[CustomStringConvertible]]
    private var items: [[CustomStringConvertible]] = []
    
    func model(at indexPath: IndexPath) throws -> Any {
        return items[indexPath.section][indexPath.row]
    }
    
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return items.count
    }
    
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return items[component].count
    }
    
    func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
        let label = UILabel()
        label.text = items[component][row].description
        label.textColor = UIColor.orange
        label.font = UIFont.preferredFont(forTextStyle: .headline)
        label.textAlignment = .center
        return label
    }
    
    func pickerView(_ pickerView: UIPickerView, observedEvent: Event<Element>) {
        Binder(self) { (adapter, items) in
            adapter.items = items
            pickerView.reloadAllComponents()
            }.on(observedEvent)
    }
}


